<template>
  <div>
    <!-- 添加或修改卖家订单对话框 -->
    <div>
      <el-dialog v-if="orderDetailForm" :title="title" :visible.sync="isOpenOrderDetail" width="80%" append-to-body
                 center
                 @close="closeOrderDetail"
      >
<!--        <el-steps :active="2" align-center>-->
        <!--          <el-step title="待发货审核" description=""></el-step>-->
        <!--          <el-step title="待发货" description=""></el-step>-->
        <!--          <el-step title="已发货" description=""></el-step>-->
        <!--          <el-step title="已收货" description=""></el-step>-->
        <!--        </el-steps>-->
        <el-divider content-position="left">基本信息</el-divider>
        <div class="essential-info">
          <el-row>
            <el-col :span="8">
              <span> 订单编号：</span> {{ orderDetailForm.orderId }}
            </el-col>
            <el-col :span="8">
              <span>买家姓名：</span>{{ orderDetailForm.buyerSignerFullname }}
            </el-col>
            <el-col :span="8">
              <span>订单创建时间：</span>{{ orderDetailForm.gmtCreate }}
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <span class="">支付时间：</span>{{ orderDetailForm.gmtPayTime }}
            </el-col>
            <el-col :span="8">
              <span class=""></span>
            </el-col>
            <el-col :span="8">
              <span>订单状态：</span>{{ orderDetailForm.orderStatus }}
            </el-col>
            <el-col :span="8">
              <span>订单类型：</span>{{ orderDetailForm.bizType }}
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="5">
              <div class="">物流费用：{{ orderDetailForm.childLogisticsAmount }}</div>
            </el-col>
            <el-col :span="4">
              <div class="">物流币种：{{ orderDetailForm.childLogisticsCurrencyCode }}</div>
            </el-col>
            <el-col :span="6">
              <div class="">全部商品金额：{{ orderDetailForm.totalProductAmount }}</div>
            </el-col>
            <el-col :span="4">
              <div class="">付款币种：{{ orderDetailForm.productUnitCurrencyCode }}</div>
            </el-col>
            <el-col :span="5">
              <div class="">付款金额：{{ orderDetailForm.payAmount }}</div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="">备注：</div>
            </el-col>
          </el-row>
        </div>
        <el-divider content-position="left" v-if="orderDetailForm.aeStoreOrderReceiptAddress">收货信息</el-divider>
        <div class="essential-info" v-if="orderDetailForm.aeStoreOrderReceiptAddress">
          <el-row>
            <el-col :span="8">
              <div class="">收件人：{{ orderDetailForm.aeStoreOrderReceiptAddress.contactPerson }}</div>
            </el-col>
            <el-col :span="8">
              <div class="">邮编：{{ orderDetailForm.aeStoreOrderReceiptAddress.zip }}</div>
            </el-col>
            <el-col :span="8">
              <div class="">电话：{{ orderDetailForm.aeStoreOrderReceiptAddress.phoneNumber }}</div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <div class="">国家/地区：{{ orderDetailForm.aeStoreOrderReceiptAddress.country }}</div>
            </el-col>
            <el-col :span="8">
              <div class="">省份：{{ orderDetailForm.aeStoreOrderReceiptAddress.province }}</div>
            </el-col>
            <el-col :span="8">
              <div class="">城市：{{ orderDetailForm.aeStoreOrderReceiptAddress.city }}</div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="">街道详细地址：{{ orderDetailForm.aeStoreOrderReceiptAddress.detailAddress }}</div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="">地址1：{{ orderDetailForm.aeStoreOrderReceiptAddress.address }}</div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="">地址2：{{ orderDetailForm.aeStoreOrderReceiptAddress.address2 }}</div>
            </el-col>
          </el-row>
        </div>
        <el-divider content-position="left">商品信息</el-divider>
        <el-table :data="productList" border stripe>
          <el-table-column label="快照" prop="productSnapUrl" align="center" width="100"></el-table-column>
          <el-table-column label="商品名称" prop="productName" align="center" width="100"></el-table-column>
          <el-table-column label="商品主图" prop="productImgUrl" align="center" width="100">
            <template slot-scope="scope">
              <imagePreview src="https://img.zhisheji.com/bbs/forum/201401/05/153945tbr7pg5torfzptso.jpg" width="60px"
                            height="60px"/>
            </template>
          </el-table-column>
          <el-table-column label="商品规格" prop="productStandard" align="center"></el-table-column>
          <el-table-column label="单价" prop="productUnitPrice" align="center" ></el-table-column>
          <el-table-column label="币种" prop="productUnitCurrencyCode" align="center"></el-table-column>
          <el-table-column label="商品编码" prop="skuCode" align="center" min-width="200"></el-table-column>
          <el-table-column label="物流费用金额" prop="childLogisticsAmount" align="center" width="100"
          ></el-table-column>
          <el-table-column label="物流费用币种" prop="childLogisticsCurrencyCode" align="center" width="100"
          ></el-table-column>
          <el-table-column label="买家备注" prop="memo" align="center" min-width="100"></el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="closeOrderDetail">确 定</el-button>
          <el-button @click="closeOrderDetail">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>

import {getOrderDetail, getAeInfo} from '@/api/order/orderApi'
import CryptoJS from "@/plugins/crypto-js.min";

export default {
  name: 'order-list',
  props: {
    id: {
      // type: Number
      // default: ''
    }
  },
  data() {
    return {
      orderList: [],//订单列表
      dialogTitle: '订单详情',//弹出框标题
      isShowOrderDetail: false, //是否展示订单详情弹出框
      isOpenOrderDetail: false,
      title: '订单详情',
      productList: [],
      orderDetailForm: '',//订单详情
      userIp: "",
      userInfo: "",
      signature: "",//秘钥签名
      params: {},
      aeInfo: {},
    }
  },
  created() {
    // document.write('<script src="https://g.alicdn.com/ali-data-safe/securesdk_v3/0.0.4/sec-min.js"><\/script>');
    // document.write('<script src="https://g.alicdn.com/sd/eco-opensecenv/2.0.3/js/axios_min.js"><\/script>');
    // document.write('<script src="https://g.alicdn.com/code/npm/@ali/ae-securesdk/0.0.3/aeSecToken.js"><\/script>');
    this.userInfo = this.$store.state.user.urserInfo
    this.getOrderDetail()
  },
  methods: {
    // 获取ae信息
    getAeData() {
      let data = {
        key: "500890a",
        userNick: this.orderDetailForm.sellerLoginId
      }
      getAeInfo(data).then(res => {
        this.aeInfo = res.data
        // this.aeInfo = {
        //   appName: "ERP3测试",
        //   appSecret: "IEu1gaoOSF1TrrXBwXKBiM39i23gvQzW",
        //   appkey: "500890",
        //   erpSellerStoreEmpowerExtend: {
        //     "refresh_token_valid_time": 1682495306000,
        //     "havana_id": "2214501798440",
        //     "expireTime": 1682408906000,
        //     "locale": "zh_CN",
        //     "user_nick": "cn1069224200touae",
        //     "accessToken": "500000016082LRcgqbvS113d24add7ffs8PuYFKGSo1Er0CdZErQCQsYSOAlpxGRO7Ww",
        //     "refresh_token": "50001000a08OJO6gApzQ1c9b97d9qAc3iyHkUCWRlehBqBnsWiiFvnzGTVXSq1Geiqfy",
        //     "userId": "2668057200",
        //     "account_platform": "seller_center",
        //     "refresh_expires_in": 172800,
        //     "expires_in": 86400,
        //     "sp": "ae",
        //     "sellerId": "2668057200",
        //     "account": "l17663846159@163.com",
        //     "code": "0",
        //     "request_id": "2102f4d116823225065436870"
        //   }
        // }
        this.getSign()
      })
    },
    // 获取秘钥
    getSign() {
      let data = this.aeInfo
      let storeData = data.erpSellerStoreEmpowerExtend
      var sSignStr = data.appSecret + "appKey" + data.appkey + "appName" + data.appName + "sellerId" + storeData.sellerId + "sessionId" +
        storeData.accessToken + "time" + storeData.expireTime + "userId" + storeData.userId + "userIp" + this.userIp + data.appSecret;
      var hash = CryptoJS.HmacSHA256(sSignStr, data.appSecret)
      let signature = CryptoJS.enc.Base64.stringify(hash)
      this.params = {
        appKey: data.appkey,
        time: storeData.expireTime,
        userId: storeData.userId,
        sellerId: storeData.sellerId,
        appName: data.appName,
        userIp: this.userIp,
        sessionId: storeData.accessToken,
        sign: signature,
      }
      this.getSecToken()
    },
    // 获取加密token
    getSecToken() {
      let secToken = window.aeSecToken;
      secToken.getAeSecTokenByBX({
        params: this.params,
        headers: {
          "Content-Type": "Application/x-www-form-urlencoded",
        },
      }).then((res) => {
        this.params.secToken = res.model
        // this.params.sign
        // this.getDecryptDataByBX()
      });
    },
    // 获取用户IP
    getUserIP(callback) {
      var ip_dups = {};
      var RTCPeerConnection = window.RTCPeerConnection
        || window.mozRTCPeerConnection
        || window.webkitRTCPeerConnection;
      var useWebKit = !!window.webkitRTCPeerConnection;
      var mediaConstraints = {
        optional: [{RtpDataChannels: true}]
      };
      // 这里就是需要的ICEServer了
      var servers = {
        iceServers: [
          {urls: "stun:stun.services.mozilla.com"},
          {urls: "stun:stun.l.google.com:19302"},
        ]
      };
      var pc = new RTCPeerConnection(servers, mediaConstraints);

      function handleCandidate(candidate) {
        var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/
        var hasIp = ip_regex.exec(candidate)
        if (hasIp) {
          var ip_addr = ip_regex.exec(candidate)[1];
          if (ip_dups[ip_addr] === undefined)
            callback(ip_addr);
          ip_dups[ip_addr] = true;
        }
      }

      // 网络协商的过程
      pc.onicecandidate = function (ice) {
        if (ice.candidate) {
          handleCandidate(ice.candidate.candidate);
        }
      };
      pc.createDataChannel("");
      //创建一个SDP(session description protocol)会话描述协议 是一个纯文本信息 包含了媒体和网络协商的信息
      pc.createOffer(function (result) {
        pc.setLocalDescription(result, function () {
        }, function () {
        });
      }, function () {
      });
      setTimeout(function () {
        var lines = pc.localDescription.sdp.split('\n');
        lines.forEach(function (line) {
          if (line.indexOf('a=candidate:') === 0)
            handleCandidate(line);
        });
      }, 1000)
    },
    // 获取解密信息
    getDecryptDataByBX() {
      let data = this.aeInfo
      let storeData = data.erpSellerStoreEmpowerExtend
      var sSignStr = this.params.secToken
      var hash = CryptoJS.HmacSHA256(sSignStr, data.appSecret)
      let signature = CryptoJS.enc.Base64.stringify(hash)
      this.params.sign = signature
      let secToken = window.aeSecToken;
      secToken.getDecryptDataByBX({
        params: this.params,
        headers: {
          "Content-Type": "Application/json",
        },
        data: {
          orderId: this.orderDetailForm.orderId,
          oaid: "JciHsGTZP3ua54df0s4tRPw"
        }
      }).then((r) => {
      });
    },
    closeOrderDetail() {
      this.isOpenOrderDetail = false
      this.$emit('orderDetailSwitch', this.isOpenOrderDetail)
    },
    //获取订单详情
    getOrderDetail() {
      this.getUserIP((ip) => {
        this.userIp = ip
      })
      let data = {
        orderId: this.id
      }
      getOrderDetail(data).then(response => {
        this.loading = false
        this.orderDetailForm = response.data
        this.productList = this.orderDetailForm.sellerChildOrderList
        this.isOpenOrderDetail = true
        this.title = '订单详情'
        // this.getAeData()
      })
    },
    openOrderDetail(e) {
      this.isShowOrderDetail = true
    }
  }
}
</script>

<style scoped>
.el-divider__text {
  font-size: 16px;
  font-weight: bold;
  color: #000;
}

.el-row {
  margin-bottom: 10px;
}

.el-col {
  border-radius: 4px;
  /*margin-right: 1px;*/
}

.el-col span {
  font-weight: bold;
  color: #333;
}

.bg-purple {
  background: #d3dce6;
}


.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
</style>
